import Vue from 'vue'
import Vuex from 'vuex'
import {getlist} from '../api/index'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list:[],
    item:[],
    car:[]
  },
  mutations: {
    // 列表
    GET_LIST(state,payload){
      state.list=payload
      // console.log(payload)
    },
    // 详情
    GET_DETAIL(state,payload){
     state.item=state.list.find(v=>v.id===payload)
    //  console.log(state.item)
    },
    // 加入购物车
    GET_CAR(state,payload){
        let carlist=state.list.find(v=>v.id===payload)
        // console.log(carlist)
      //  let data=localStorage.setItem('data',JSON.stringify(carlist))
      let data= state.car.find(v=>v.id===carlist.id)  
      if(data){
         data.count++
        }else{
          state.car.push({
            ...carlist,
            count:1,
          })
        }
    //  console.log(state.car)
      
     },
    //  购物车加加
    GET_CARADD(state,payload){
      let caradd=state.car.find(v=>v.id===payload)
      caradd.count++
    },
    //  购物车减减
    GET_CARREM(state,payload){
      let caradd=state.car.find(v=>v.id===payload)
     if(caradd.count<=1){
     window.confirm('确定删除吗?')?state.car=state.car.filter(v=>v.id!==payload):''
     }else{
      caradd.count--
     }
    }
  },
  actions: {
    async SET_LIST({commit}){
      const resp=await getlist()
      commit('GET_LIST',resp.data.data)
    }
  },
  modules: {
  }
})
